package com.xuehu.filter;

import com.xuehu.pojo.User;
import com.xuehu.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;

        //过滤器,从session获取用户
        User user = (User)servletRequest.getSession().getAttribute(Constants.USER_SESSION);

        if (user == null) { //已经被移除或者注销了,或者未登录
            System.out.println("以拦截-----");
            servletResponse.sendRedirect(servletRequest.getContextPath() + "/error.jsp");
        } else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {

    }
}
